import cv2 as cv
import copy
import matplotlib.pyplot as plt

filename1 = r'E:\python\data\pic2.png'
filename2 = r'E:\python\data\pic6.png'

img1=cv.imread(filename1)#读图
img2=cv.imread(filename2)
gray1=cv.cvtColor(img1,cv.COLOR_BGR2GRAY)#转成灰度图像
gray2=cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
hist1=cv.calcHist([gray1],[0],None,[256],[0,256])#计算灰度直方图
hist2=cv.calcHist([gray2],[0],None,[256],[0,256])

plt.plot(hist1)
plt.xlim([0,256])
plt.title("pic2-hist")
plt.show()

plt.plot(hist2)
plt.xlim([0,256])
plt.title("pic6-hist")
plt.show()

Gauss_pic2=cv.GaussianBlur(gray1,(3,3),0)
_,gray_OTSU_pic2=cv.threshold(Gauss_pic2,125,255,cv.THRESH_OTSU)
element_pic2=cv.getStructuringElement(cv.MORPH_CROSS,(3,3))
pic2=cv.morphologyEx(gray_OTSU_pic2,cv.MORPH_CROSS,element_pic2)
cv.imshow("OTSU-pic2",pic2)

Gauss_pic6=cv.GaussianBlur(gray2,(3,3),0)
_,gray_OTSU_pic6=cv.threshold(Gauss_pic6,125,255,cv.THRESH_OTSU)
element_pic6=cv.getStructuringElement(cv.MORPH_CROSS,(3,3))
pic6=cv.morphologyEx(gray_OTSU_pic6,cv.MORPH_CROSS,element_pic6)
cv.imshow("OTSU-pic6",pic6)

cv.waitKey()
cv.destroyAllWindows()